package com.xmut.bs.handaccount.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.base.ToolbarBaseActivity;
import com.xmut.bs.handaccount.bmob.Adv;
import com.xmut.bs.handaccount.util.CommonUtil;
import com.xmut.bs.handaccount.util.ImageUtils;
import com.xmut.bs.handaccount.util.SDCardUtil;
import com.xmut.bs.handaccount.util.StringUtil;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.xmut.bs.handaccount.base.Constants.PARAM_EDIT;

/**
 * Description
 * Created by Dollkey on 2018/4/21.
 */

public class AddAdvActivity extends ToolbarBaseActivity {
    @BindView(R.id.img)
    ImageView mImg;
    @BindView(R.id.adv_url_et)
    MaterialEditText mAdvUrlEt;

    private ProgressDialog insertDialog;
    private ProgressDialog saveDialog;
    private String mImgUrl;
    private Adv mAdv;

    @Override
    protected String getSubTitle() {
        return mAdv==null?"添加广告":"编辑广告";
    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_add_adv;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        saveDialog = new ProgressDialog(this);
        saveDialog.setMessage("正在保存...");
        if (mAdv != null) {
            GlideApp.with(mImg).load(mAdv.getImgUrl()).placeholder(R.color.grey300).error(R.color.grey300).centerCrop().into(mImg);
            mAdvUrlEt.setText(mAdv.getAdvUrl());
        }
    }

    @Override
    protected void initParams(Intent intent) {
        mAdv = (Adv) intent.getSerializableExtra(PARAM_EDIT);
    }

    @OnClick({R.id.img, R.id.right_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img:
                callGallery();
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_add, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add:
                if (mAdv == null)
                    save();
                else {
                    update();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void update() {
        saveDialog.show();
        if (StringUtil.isNull(mImgUrl)) {
            mAdv.setAdvUrl(mAdvUrlEt.getText().toString().trim());
            mAdv.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    saveDialog.dismiss();
                    if (e == null) {
                        showToast("保存成功");
                        setResult(Activity.RESULT_OK);
                        finish();
                    } else {
                        showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                    }
                }
            });
        } else {
            final BmobFile bmobFile = new BmobFile(new File(mImgUrl));
            bmobFile.uploadblock(new UploadFileListener() {

                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        mAdv.setAdvUrl(mAdvUrlEt.getText().toString().trim());
                        mAdv.setImgUrl(bmobFile.getFileUrl());
                        mAdv.update(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                saveDialog.dismiss();
                                if (e == null) {
                                    showToast("保存成功");
                                    setResult(Activity.RESULT_OK);
                                    finish();
                                } else {
                                    showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                                }
                            }
                        });
                    } else {
                        saveDialog.dismiss();
                        showToast("上传文件失败：" + e.getMessage());
                    }

                }

                @Override
                public void onProgress(Integer value) {
                }
            });
        }
    }

    private void save() {
        if (StringUtil.isNull(mImgUrl)) {
            showToast("请选择图片");
            return;
        }
        saveDialog.show();
        final BmobFile bmobFile = new BmobFile(new File(mImgUrl));
        bmobFile.uploadblock(new UploadFileListener() {

            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Adv adv = new Adv(bmobFile.getFileUrl(), mAdvUrlEt.getText().toString().trim());
                    adv.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            saveDialog.dismiss();
                            if (e == null) {
                                showToast("保存成功");
                                setResult(Activity.RESULT_OK);
                                finish();
                            } else {
                                showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                            }
                        }
                    });
                } else {
                    saveDialog.dismiss();
                    showToast("上传文件失败：" + e.getMessage());
                }

            }

            @Override
            public void onProgress(Integer value) {
            }
        });
    }

    /**
     * 调用图库选择
     */
    private void callGallery() {
        //调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");// 相片类型
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 1) {
                    //处理调用系统图库
                    insertImagesSync(data);
                }
            }
        }
    }

    /**
     * 异步方式插入图片
     */
    private void insertImagesSync(final Intent data) {
        insertDialog.show();
        Observable
                .create(new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
                        try {
                            int width = CommonUtil.getScreenWidth(mContext);
                            int height = CommonUtil.getScreenHeight(mContext);
                            Uri uri = data.getData();
                            Bitmap bitmap;
                            ContentResolver cr = mContext.getContentResolver();
                            Cursor cursor = cr.query(uri, null, null, null, null);
                            cursor.moveToFirst();
                            String img_path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                            bitmap = ImageUtils.getSmallBitmap(img_path, width, height);//压缩图片
                            cursor.close();
                            subscriber.onNext(SDCardUtil.saveToSdCard(bitmap));
                            subscriber.onCompleted();
                        } catch (Exception e) {
                            e.printStackTrace();
                            subscriber.onError(e);
                        }
                    }
                })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        insertDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        insertDialog.dismiss();
                        showToast("图片添加失败" + e.getMessage());
                    }

                    @Override
                    public void onNext(String imagePath) {
                        mImgUrl = imagePath;
                        GlideApp.with(mImg).load(imagePath).placeholder(R.color.grey300).error(R.color.grey300).centerCrop().into(mImg);
                    }
                });
    }
}
